package com.shipwe.loans.ui.activity

import android.net.Uri
import android.view.View
import androidx.camera.core.AspectRatio
import androidx.camera.core.CameraSelector
import androidx.camera.core.ImageCapture
import androidx.camera.core.ImageCaptureException
import androidx.camera.core.Preview
import androidx.camera.lifecycle.ProcessCameraProvider
import androidx.core.content.ContextCompat
import com.shipwe.loans.MyApps
import com.shipwe.loans.databinding.ActivityCameraFaceBinding
import com.shipwe.loans.pro.ShipweActivity
import com.shipwe.loans.ui.presenter.UploadPresenter
import com.shipwe.loans.ui.view.IUploadView
import com.shipwe.loans.utils.ShipweTitleBarUtil
import com.shipwe.loans.utils.AppLoadImageUtil
import com.shipwe.loans.utils.event.AppEventPointType
import com.shipwe.loans.utils.imgcovert.ImageConvert
import com.shipwe.loans.utils.log.ShipweLogger
import java.io.File
import java.util.concurrent.ExecutorService
import java.util.concurrent.Executors

/**
 * Shipwe
 * @Author wwdeng
 * @CreateTime: 2024/11/22 17:12
 * @Annotation：自拍照
 */
class ActivityCameraFace: ShipweActivity(),IUploadView {
    lateinit var binding: ActivityCameraFaceBinding
    var presenter: UploadPresenter? = null

    private lateinit var cameraExecutor: ExecutorService
    private var imageCapture: ImageCapture? = null
    private var imgUri: Uri? = null
    private var imgUsePath = ""


    override fun getShipweRootView(): View {
        binding = ActivityCameraFaceBinding.inflate(layoutInflater)
        return binding.root
    }

    override fun initShipweView() {
        ShipweTitleBarUtil.setStatusBarLightMode(this, false)
        binding.faceTitleView.setPadding(0, ShipweTitleBarUtil.getStatusBarHeight(),0,0)

        cameraExecutor = Executors.newSingleThreadExecutor()
        startCameraFace()
    }

    override fun initShipweListener() {
        binding.faceBack.setOnClickListener {
            finish()
        }
        binding.faceCustomer.setOnClickListener {
            val eventTitle = "SelfieCamera Page"
            showCustomerDialog(eventTitle)
            appEventPointRequestAction(AppEventPointType.CLICK.SHIPWE_CLICK_CUSTOMER,eventTitle)
        }
        //拍照
        binding.faceTake.setOnClickListener {
            appEventPointRequestAction(AppEventPointType.CLICK.SHIPWE_CLICK_CAMERA_TAKE_PHOTO,"SelfieCamera Page")
            takeCameraFaceFilePhoto()
        }

        //重拍
        binding.faceRemake.setOnClickListener {
            appEventPointRequestAction(AppEventPointType.CLICK.SHIPWE_CLICK_STEP_SELFIE_REMAKE,"")
            showCameraFaceTakeView()
        }

        //使用
        binding.faceUseView.setOnClickListener {
            appEventPointRequestAction(AppEventPointType.CLICK.SHIPWE_CLICK_STEP_SELFIE_USE_PHOTO, imgUsePath)
            showShipweLoading()
            // 图片处理
            ImageConvert.covert(context = this, uri = imgUri) { localPath, bitmap ->
                if (localPath != null){
                    ShipweLogger.e("imageConvert success>>>>>>>$localPath")
                    presenter!!.submitUploadImageAction(localPath)
                }
            }
        }
    }

    override fun initShipweData() {
        presenter = UploadPresenter(this)
    }

    /**
     * 打开相机预览
     */
    private fun startCameraFace() {
        showCameraFaceTakeView()
        val cameraProviderFuture = ProcessCameraProvider.getInstance(this)
        cameraProviderFuture.addListener(Runnable {
            val cameraProvider: ProcessCameraProvider = cameraProviderFuture.get()
            val preview = Preview.Builder()
                .setTargetAspectRatio(AspectRatio.RATIO_16_9)
                .build()
                .also {
                    it.setSurfaceProvider(binding.faceCameraView.surfaceProvider)
                }
            imageCapture = ImageCapture.Builder().build()
            //打开前置摄像头
            val cameraSelector = CameraSelector.DEFAULT_FRONT_CAMERA
            try {
                cameraProvider.unbindAll()
                cameraProvider.bindToLifecycle(this, cameraSelector, preview,imageCapture)
            } catch(exc: Exception) {
            }
        }, ContextCompat.getMainExecutor(this))
    }

    /**
     * 拍照并保存到本地
     */
    private fun takeCameraFaceFilePhoto(){
        if (imageCapture != null){
            //创建文件
            val filePath = MyApps.app.filesDir.absolutePath
            val outputFile = File(filePath,"${System.currentTimeMillis()}.jpg")
            if (!outputFile.exists()){
                outputFile.mkdir()
            }
            //创建输出选项对象
            val metadata = ImageCapture.Metadata().apply {
                // 当为前置摄像头时镜像；前置摄像头预览时默认就是镜像
                isReversedHorizontal = true
            }
            //创建文件
            val outputFileOptions = ImageCapture.OutputFileOptions.Builder(outputFile).setMetadata(metadata).build()
            //开始拍照
            imageCapture!!.takePicture(outputFileOptions,ContextCompat.getMainExecutor(this),object : ImageCapture.OnImageSavedCallback{
                override fun onImageSaved(outputFileResults: ImageCapture.OutputFileResults) {
                    imgUri = outputFileResults.savedUri
                    ShipweLogger.e("take photo complete>>>>>>>${imgUri!!.path}")
                    imgUsePath = imgUri!!.path!!
                    AppLoadImageUtil.instance.loadImageUrl(this@ActivityCameraFace,binding.facePreview,imgUsePath,0)
                    showCameraFaceCompleteView()
                }
                override fun onError(exception: ImageCaptureException) {
                    ShipweLogger.e("take photo failed >>>>>>>${exception.message}")
                }
            })
        }
    }

    /**
     * 显示拍照样式
     */
    private fun showCameraFaceTakeView(){
        binding.facePreview.visibility = View.GONE
        binding.faceTake.visibility = View.VISIBLE
        binding.faceRemake.visibility = View.INVISIBLE
        binding.faceUseView.visibility = View.INVISIBLE
    }

    /**
     * 显示拍照完成页面
     */
    private fun showCameraFaceCompleteView(){
        binding.facePreview.visibility = View.VISIBLE
        binding.faceTake.visibility = View.INVISIBLE
        binding.faceRemake.visibility = View.VISIBLE
        binding.faceUseView.visibility = View.VISIBLE
    }

    /**
     * 图片上传完成
     */
    override fun showUploadImageSuccess(imgPath: String, imgUrl: String) {
        val intent = intent
        intent.putExtra("imgLocalPath",imgUsePath)
        intent.putExtra("imgUrl",imgUrl)
        setResult(RESULT_OK,intent)
        finish()
    }

    override fun onStart() {
        super.onStart()
        appEventPointRequestAction(AppEventPointType.PAGE.SHIPWE_PAGE_STEP_SELFIE_CAMERA_START)
    }

    override fun onDestroy() {
        super.onDestroy()
        appEventPointRequestAction(AppEventPointType.PAGE.SHIPWE_PAGE_STEP_SELFIE_CAMERA_END)
        cameraExecutor.shutdown()
    }
}